package com.data.config.rest;

/*import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.registry.NacosRegistration;
import com.alibaba.nacos.api.exception.NacosException;*/

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * Description
 * <br> 获取提交至git的版本信息
 * @author chengang
 **/
@RestController
@RequestMapping("/api/git")
@Api(tags = {"Agit版本信息--当前代码"})
@Slf4j
public class GitVersionRest {

    /*@Autowired
    NacosDiscoveryProperties nacosDiscoveryProperties;
    @Autowired
    NacosRegistration nacosRegistration;
    @Autowired
    InetUtils inetUtils;*/

    @ApiOperation(value = "获取GIT信息", notes = "获取GIT信息")
    @RequestMapping(value = "/version", method= GET,produces="text/plain;charset=UTF-8")
    public String versionInformation() {
        return readGitProperties();
    }
    private String readGitProperties() {
        ClassLoader classLoader = getClass().getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("git.properties");
        try {
            return readFromInputStream(inputStream);
        } catch (Exception e) {
            log.error("readGitProperties方法异常",e);
            return "Version information could not be retrieved";
        }
    }

    private String readFromInputStream(InputStream inputStream)
            throws IOException {
        StringBuilder resultStringBuilder = new StringBuilder();
        String line ;
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        while ((line = br.readLine()) != null) {
            resultStringBuilder.append(line).append("\n");
        }

        return resultStringBuilder.toString();
    }
    @ApiOperation(value = "NACOS下线", notes = "NACOS下线")
    @RequestMapping(value = "/nacos/deregister", method= GET,produces="text/plain;charset=UTF-8")
    public String deregisterInstance() {
        /*String ipI = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
        if(!"127.0.0.1".equals(ipI)){
            log.info("非法访问接口ip->{}", StringUtils.isNotEmpty(ipI)?ipI:"");
            return "非法访问接口->>>ip:"+ipI;
        }
        String serviceName = nacosDiscoveryProperties.getService();
        String groupName = nacosDiscoveryProperties.getGroup();
        String clusterName = nacosDiscoveryProperties.getClusterName();
        String ip = nacosDiscoveryProperties.getIp();
        int port = nacosDiscoveryProperties.getPort();
        log.info("deregister from nacos, serviceName:{}, groupName:{}, clusterName:{}, ip:{}, port:{}", serviceName, groupName, clusterName, ip, port);
        try {
            nacosRegistration.getNacosNamingService().deregisterInstance(serviceName, groupName, ip, port, clusterName);
        } catch (NacosException e) {
            log.error("deregister from nacos error", e);
            return "error";
        }*/
        return "success";
    }



    /**
     * 修改项目日志输出级别
     *
     * @param rootLevel 全局日志级别
     * @param singleLevel 某个类日志级别
     * @param singlePath 需要单独设置日志输出级别的类的全限定名（例:com.iot）
     * @return
     */
    @ApiOperation(value = "changeLogLevel")
    @GetMapping("changeLevel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rootLevel",
                    value = "root,全局级别:ALL,TRACE,DEBUG,INFO,WARN,ERROR,OFF", required = false),
            @ApiImplicitParam(name = "singleLevel",
                    value = "单独设置类日志级别:ALL,TRACE,DEBUG,INFO,WARN,ERROR,OFF", required = false),
            @ApiImplicitParam(name = "singlePath",
                    value = "单独类路径:com.kakarote.core.common.GitVersionRest",
                    required = false)})
    public String changeLevel(String rootLevel, String singleLevel, String singlePath) {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        log.error(" changeLevel set log rootLevel:{},singleLevel:{},singlePath:{}", rootLevel, singleLevel, singlePath);
        if (!StringUtils.isEmpty(rootLevel)) {
            // 设置全局日志级别
            ch.qos.logback.classic.Logger logger = loggerContext.getLogger("root");
            logger.setLevel(Level.toLevel(rootLevel));
        }

        if (!StringUtils.isEmpty(singleLevel)) {
            // 设置某个类日志级别-可以实现定向日志级别调整
            ch.qos.logback.classic.Logger vLogger = loggerContext.getLogger(singlePath);
            if (vLogger != null) {
                vLogger.setLevel(Level.toLevel(singleLevel));
            }
        }
        return "success";
    }


}
